package cn.zzm.scheduleMessage;

import cn.zzm.common.Constants;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ScheduledMessage;

import javax.jms.*;

/**
 * @program: study
 * @description:延时队列
 * @author: 周昭名
 * @create: 2019-04-07 22:11
 **/
public class JmsSmProducer {

    public static void main(String[] args) {
        /*连接工厂*/
        ConnectionFactory connectionFactory;
        /*连接*/
        Connection connection = null;
        /*会话*/
        Session session;
        /*目的地*/
        Destination destination;
        /*生产者*/
        MessageProducer messageProducer;

        /*实例化连接工厂*/
        connectionFactory = new ActiveMQConnectionFactory(Constants.USERNAME, Constants.PASSWORD, Constants.BROKEURL);
        try {
            /*通过工厂获取连接*/
            connection = connectionFactory.createConnection();
            connection.start();
            /* 创建session
             * 第一个参数表示是否使用事务，第二次参数表示是否自动确认*/
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            /*创建一个topic*/
            destination = session.createQueue("scheduleMsgQueue");
            /*创建消息发送者*/
            messageProducer = session.createProducer(destination);


            System.out.println("消息发送中...");
            String msg = System.currentTimeMillis() + "_延迟消息序号";
            TextMessage textMessage = session.createTextMessage(msg);
            //延迟10s发送 发10次 间隔5s
            long delay = 5 * 1000;
            long period = 5 * 1000;
            int repeat = 9;
            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY,delay);
            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD,period);
            textMessage.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT,repeat);
            //textMessage.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON,"0 * * * *");
            messageProducer.send(textMessage);
            System.out.println(System.currentTimeMillis());


        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            if (connection!=null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

